// 云函数入口文件
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context })
  
  let body = event;
  if (event.body != undefined) {
  	body = JSON.parse(event.body)
  }

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken)
    if (!uid) {
      return { code: 403, msg: '身份验证失败' }
    }

    // 2. 获取数据库实例
    const db = uniCloud.database()

    // 3. 解析前端传递的操作类型
	const actionType = ["skip","complete"]
    const { action, nolongerPop } = body // action: 'skip' 或 'completeTest'
	//字段校验
	if (action === undefined || nolongerPop === undefined){
		return{
			code:-2,
			msg:"缺少必要参数"
		}
	}
	if(!actionType.includes(action)){
		return{
			code:-3,
			msg:"无效action"
		}
	}
	if(nolongerPop !==0 && nolongerPop !==1){
		return{
			code:-3,
			msg:"无效nolonerPop"
		}
	}
	
    let newFrequency = 0 // 默认保持 0

    if (action === 'complete' || nolongerPop === 1) {
      newFrequency = 1 // 完成测试或勾选 nolongerPop 时设为 1
    }

    // 4. 更新 test_frequency 字段
    await db.collection('uni-id-users').doc(uid).update({
      test_frequency: newFrequency
    })

    return { code: 0, msg: '更新成功', test_frequency: newFrequency }

  } catch (e) {
  console.error('更新失败:', e);
  return { code: 500, msg: '服务器错误', error: e.message, stack: e.stack };
}

}
